package com.itcz.maker.generator;

import java.io.*;

/**
 * jar包生成器
 */
public class JarGenerator {
    public static void doGenerate(String projectDir) throws IOException, InterruptedException {
        // 清理之前的构建并打包
        // 注意不同的系统，执行的命令不同
        String winMavenCommand = "mvn.cmd clean package -DskipTests=true";
        String otherMavenCommand = "mvn clean package -DskipTests=true";
        String mavenCommand = winMavenCommand;

        // 通过空格拆分字符串得到命令
        ProcessBuilder processBuilder = new ProcessBuilder(mavenCommand.split(" "));
        processBuilder.directory(new File(projectDir));

        try {
            // 执行命令
            Process process = processBuilder.start();

            //读取命令输出
            // 1.获取输入流对象
            InputStream inputStream = process.getInputStream();
            // 2.将输入流对象放入缓冲输入流
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            // 3.通过缓冲输入流对象读取每一行数据，不为空则打印命令输出信息
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            // 等待命令完成
            int result = process.waitFor();
            System.out.println("命令执行结束，退出码：" + result);
        } catch (IOException e) {
            throw new IOException(e);
        } catch (InterruptedException e) {
            // 恢复中断状态
            Thread.currentThread().interrupt();
            throw new InterruptedException();
        }
    }
}
